<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-present http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\logic\UserLogic;
use app\admin\model\RoleModel;
use app\admin\model\RoleUserModel;
use app\admin\model\UserModel;
use app\admin\service\EmailService;
use app\admin\controller\UserController;
use think\db\Query;
use think\Validate;

/**
 * Class UserMineController
 * @package app\admin\controller
 * @adminMenuRoot(
 *     'name'   => '管理组',
 *     'action' => 'default',
 *     'parent' => 'user/AdminIndex/default',
 *     'display'=> false,
 *     'order'  => 10000,
 *     'icon'   => '',
 *     'remark' => '管理组'
 * )
 */
class UserMineController extends UserController
{

    /**
     * 管理员列表
     * @adminMenu(
     *     'name'   => '管理员',
     *     'parent' => 'user/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员管理',
     *     'param'  => ''
     * )
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $content = hook_one('admin_user_index_view');

        if (!empty($content)) {
            return $content;
        }

        /**搜索条件**/
        $userRole = $this->request->param('user_role');
        $userName = $this->request->param('user_name');
        $userLogin = $this->request->param('user_login');
        $userEmail = trim($this->request->param('user_email',''));

        $model = new UserModel();
        $query = $model->alias('u');
        $query->leftJoin('cmf_role_user ru', 'ru.user_id = u.id');
        $query->leftJoin('cmf_role r', 'r.id = ru.role_id');
        $users = $query->field('u.*, r.name')
            ->where('user_type', 1)
            ->where(function (Query $query) use ($userRole, $userName, $userLogin, $userEmail) {
                if ($userRole) {
                    $query->where('r.id', $userRole);
                }
                if ($userName) {
                    $query->where('user_nickname', 'like', "%$userName%");
                }
                if ($userLogin) {
                    $query->where('user_login', 'like', "%$userLogin%");
                }
                if ($userEmail) {
                    $query->where('user_email', 'like', "%$userEmail%");
                }
            })
            ->order("id DESC")
            ->paginate(10);
        $users->appends(['user_login' => $userLogin, 'user_email' => $userEmail]);
        // 获取分页显示
        $page = $users->render();

        $roles = RoleModel::where('status', 1)->select();
        $this->assign("roles", $roles);

        $this->assign("page", $page);
        $this->assign("users", $users);
        return $this->fetch();
    }

    /**
     * 管理员添加提交
     * @adminMenu(
     *     'name'   => '管理员添加提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员添加提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            $roleId = $this->request->param('role_id', 0, 'intval');
            if (!empty($roleId)) {
                $data   = $this->request->param();
                $result = $this->validate($data, 'User.add');
                if ($result !== true) {
                    $this->error($result);
                } else {
                    $data['user_pass']       = cmf_password($data['user_pass']);
                    $data['create_time']     = time();
                    $data['last_login_time'] = $data['create_time'];
                    $userId            = UserModel::strict(false)->insertGetId($data);
                    if ($userId !== false) {
                        //$role_user_model=M("RoleUser");
                        // foreach ($roleIds as $roleId) {
                            if (cmf_get_current_admin_id() != 1 && $roleId == 1) {
                                $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                            }
                            RoleUserModel::insert(["role_id" => $roleId, "user_id" => $userId]);
                        // }
                        $this->success(lang('ADD_SUCCESS'), url('UserMine/index'));
                    } else {
                        $this->error(lang('ADD_FAILED'));
                    }
                }
            } else {
                $this->error("请为此用户指定角色！");
            }

        }
    }


    /**
     * 管理员编辑提交
     * @adminMenu(
     *     'name'   => '管理员编辑提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员编辑提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            if(!UserLogic::isCreator()){
                $this->error('为了网站的安全，非网站创建者不可编辑');
            }
            $roleId = $this->request->param('role_id', 0, 'intval');
            if (!empty($roleId)) {
                $data = $this->request->param();
                if (empty($data['user_pass'])) {
                    unset($data['user_pass']);
                } else {
                    $data['user_pass'] = cmf_password($data['user_pass']);
                }
                $result = $this->validate($data, 'User.edit');

                if ($result !== true) {
                    // 验证失败 输出错误信息
                    $this->error($result);
                } else {
                    $userId = $this->request->param('id', 0, 'intval');
                    $result = UserModel::strict(false)->where('id', $userId)->save($data);
                    if ($result !== false) {
                        RoleUserModel::where("user_id", $userId)->delete();
                        // foreach ($roleIds as $roleId) {
                            if (cmf_get_current_admin_id() != 1 && $roleId == 1) {
                                $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                            }
                            RoleUserModel::insert(["role_id" => $roleId, "user_id" => $userId]);
                        // }
                        $this->success(lang('EDIT_SUCCESS'));
                    } else {
                        $this->error(lang('EDIT_FAILED'));
                    }
                }
            } else {
                $this->error("请为此用户指定角色！");
            }

        }
    }

}
